<template>
  <a-modal :title="title" :width="width" :visible="visible" @ok="handleOk" :okButtonProps="{ class: { 'jee-hidden': disableSubmit } }" @cancel="handleCancel" cancelText="关闭" :destroyOnClose="true">
    <StandardPriceForm v-if="visible" ref="registerForm" @ok="submitCallback" :formDisabled="disableSubmit" :formBpm="false"></StandardPriceForm>
  </a-modal>
</template>

<script lang="ts" setup>
  import { ref, nextTick, defineExpose, watch } from 'vue';
  import StandardPriceForm from './StandardPriceForm.vue'
  
  const title = ref<string>('');
  const width = ref<number>(800);
  const visible = ref<boolean>(false);
  const disableSubmit = ref<boolean>(false);
  const registerForm = ref();
  const emit = defineEmits(['register', 'success']);
  
  let currentRecord = null;
  let isAddMode = false;

  /**
   * 新增
   */
  function add() {
    title.value = '新增';
    isAddMode = true;
    currentRecord = null;
    visible.value = true;
  }
  
  /**
   * 编辑
   * @param record
   */
  function edit(record) {
    title.value = disableSubmit.value ? '详情' : '编辑';
    isAddMode = false;
    currentRecord = record;
    visible.value = true;
  }
  
  // 监听 visible 变化，当 Modal 打开时触发表单操作
  watch(visible, async (newVal) => {
    if (newVal) {
      // 等待组件渲染完成
      await nextTick();
      await nextTick();
      if (registerForm.value) {
        if (isAddMode) {
          await registerForm.value.add();
        } else {
          await registerForm.value.edit(currentRecord);
        }
      }
    }
  });
  
  /**
   * 确定按钮点击事件
   */
  function handleOk() {
    registerForm.value.submitForm();
  }

  /**
   * form保存回调事件
   */
  function submitCallback() {
    handleCancel();
    emit('success');
  }

  /**
   * 取消按钮回调事件
   */
  function handleCancel() {
    visible.value = false;
  }

  defineExpose({
    add,
    edit,
    disableSubmit,
  });
</script>

<style>
  /**隐藏样式-modal确定按钮 */
  .jee-hidden {
    display: none !important;
  }
</style>
